package starpay

import (
	"context"
	"encoding/json"

	xerrors "gitee.com/liuxuezhan/ar-platform/admin-api/pkg/xerrors/assets"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/starpay/starpay/tool"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StarpayPayoutNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// starpay提现回调通知
func NewStarpayPayoutNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StarpayPayoutNotifyLogic {
	return &StarpayPayoutNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StarpayPayoutNotifyLogic) StarpayPayoutNotify(req *types.StarpayWithdrawNotifyReq) (resp *types.StarpayWithdrawNotifyResp, err error) {
	b, _ := sonic.Marshal(req)

	var SecretKey = "0eb120494eeef66a6d00ebd0ad2565bb"

	sign, err := tool.GenerateSignature(req.MerchantNo, req.Params, req.SignType, SecretKey, req.Timestamp)

	if sign != req.Sign {
		logc.Error(l.ctx, "signature verification failed: ", sign, req.Sign)
		return nil, xerrors.ErrSignVerifyFailed
	}
	var data types.Params
	err = json.Unmarshal([]byte(req.Params), &data)
	if err != nil {
		return nil, err
	}
	// 根据订单状态处理业务逻辑
	if data.Status == 1 {
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawSuccess(l.ctx, &rpc.SuccessWithDrawReq{OrderNo: data.MerchantRef, Data: string(b)})
	}
	if data.Status == 2 {
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawFail(l.ctx, &rpc.FailWithDrawReq{OrderNo: data.MerchantRef, Data: string(b)})
	}
	if err != nil {
		logc.Error(l.ctx, err, string(b))
	}

	return
}
